package com.qf.blog.service.impl;

import com.qf.blog.entity.Post;
import com.qf.blog.service.ICommentService;
import com.qf.blog.service.IPostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

// 这里完成它的帖子分数计算
@Service
public class PostScoreService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private String postScoreKey = "blog:post:score";

    @Autowired
    private IPostService postService;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private LikeService likeService;

    public void addPostToRedis(Integer id) {
        stringRedisTemplate.opsForSet().add(postScoreKey, id.toString());
    }

    public Long getPostSize() {
        return stringRedisTemplate.opsForSet().size(postScoreKey);
    }

    public void updatePostScore() {

        while (getPostSize() > 0) {

            // 1.先从redis中取出一个帖子,弹出来后也就意味着从redis中删除了
            Integer postId = Integer.parseInt(stringRedisTemplate.opsForSet().pop(postScoreKey));

            // 2.查询帖子的点赞数量
            Long likeCount = likeService.likeSize(postId, 1);

            // 3.查询梯子的评论数量
            Long commentCount = commentService.getPostCommentSize(postId);

            // 4.查询帖子是否置顶
            Post post = postService.getById(postId);

            // 5.计算帖子因素
            Long x = commentCount * 20; // 评论数量
            Long y = likeCount * 40; // 点赞数量(点赞的权重要高一点)
            Long z = post.getType() == 1 ? 100L : 0L; // 如果帖子被置顶了在家100的分数

            // 6.根据因素计算分数
            double source = Math.log10(Math.max((x + y + z), 1));

            // 7、跟新MyQL中帖子的分数
            postService.updatePostSource(postId,source);
        }
    }

    // 0.0 --》都是0
    // 1.7781512503836436   -->只有3个评论
    // 2.0791812460476247   --->只有3个点赞
    // 2.255272505103306 --->3个评论，3个点赞
    // 2.4471580313422194 --->3个评论，3个点赞，置顶
    public static void main(String[] args) {
        Long x = 3L * 20; // 评论数量
        Long y = 3L * 40; // 点赞数量(点赞的权重要高一点)
        Long z = 1L == 1 ? 100L : 0L; // 如果帖子被置顶了在家100的分数
        double source = Math.log10(Math.max((x + y + z), 1));
        System.out.println(source);
    }
}
